// 最大N个数和最小N个数的和
// 题目链接：https://fcqian.blog.csdn.net/article/details/127417952
// 做题思路：
// 先用哈希表，将数统计好，并按从小到大排序，返回数组
// 将数组切割，从头切一刀，从尾再切一刀，结束

const HashMap = require('./hashmap.js');
class CountN {
    constructor(arrayLength) {
        this.arrayLength = arrayLength;
        this.arr = [];
        this.DEBUG = true;
    }

    add(array) {
        if (array.length != this.arrayLength) {
            throw new Error('[countN] ERROR!! Array length != arrayLength');
        }

        let hashMap = new HashMap(true);
        for (let n of array) {
            hashMap.add(n);
        }

        this.arr = hashMap.keys().sort((a, b) => a - b);

        if (this.DEBUG) {
            console.log(`[HashMap] add complete`);
            console.log(`${this.arr}`);
        }
    }

    count(n) {
        if (this.arr.length <= n * 2) {
            return -1;
        }

        const mins = this.arr.slice(0, n);
        const maxs = this.arr.slice(this.arr.length - n, this.arr.length);

        let count = 0;
        count = mins.reduce((acc, cur) => acc + cur, count);
        count = maxs.reduce((acc, cur) => acc + cur, count);

        return count;
    }
}

let countN = new CountN(5);
countN.add([95, 88, 83, 64, 100]);
let count = countN.count(3);
console.log(`test 3 result: ${count}`);

console.log(`-----------------------`);

let countNN = new CountN(5);
countNN.add([3, 2, 3, 4, 2]);
console.log(`test 1 result: ${countNN.count(1)}`);
